package com.jarvis.pzz.modules.buyshop;

import android.content.Context;
import android.content.Intent;
import android.support.v7.view.ContextThemeWrapper;
import android.support.v7.widget.PopupMenu;
import android.telephony.PhoneNumberUtils;
import android.text.TextUtils;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.jarvis.pzz.R;
import com.jarvis.pzz.common.BaseActivity;
import com.jarvis.pzz.common.ResponseData;
import com.jarvis.pzz.models.InitFindShopModel;
import com.jarvis.pzz.models.ShopsListByFilterModel;
import com.jarvis.pzz.modules.buyshop.adapter.BuyShopAdapter;
import com.jarvis.pzz.modules.completed.ReleaseCompletedActivity;
import com.jarvis.pzz.modules.findshop.model.FindFacilitiesModel;
import com.jarvis.pzz.seervers.RequestService;
import com.jarvis.pzz.util.SharePreferenceKey;
import com.jarvis.pzz.util.SharePreferenceUtils;
import com.jarvis.pzz.util.net.RequestApi;
import com.jarvis.pzz.widget.ScrollGridView;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import butterknife.BindView;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class BuyShopActivity extends BaseActivity implements View.OnClickListener {
    @BindView(R.id.rel_left)
    RelativeLayout rel_left;
    @BindView(R.id.lin_title)
    RelativeLayout lin_title;
    @BindView(R.id.et_buy_jg)
    EditText et_buy_jg;
    @BindView(R.id.et_buy_mj)
    EditText et_buy_mj;
    @BindView(R.id.ll_spinner_qy)
    LinearLayout ll_spinner_qy;
    @BindView(R.id.tv_buy_qy)
    TextView tv_buy_qy;
    @BindView(R.id.et_buy_phone)
    EditText et_buy_phone;
    @BindView(R.id.et_buy_jy)
    EditText et_buy_jy;
    @BindView(R.id.sgv_ss)
    ScrollGridView sgv_ss;
    @BindView(R.id.tv_buy_publish)
    TextView tv_buy_publish;

    private String buy_qy = "";//期望区域
    private BuyShopAdapter buyShopAdapter;
    private List<FindFacilitiesModel> findFacilitiesModels;
    private List<InitFindShopModel.areaListBean> areaListBeen;
    private RequestService service;

    @Override
    public int getLayoutId() {
        return R.layout.activity_buy_shop;
    }

    @Override
    public void initData() {
        sgv_ss.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, final int position, long id) {
                ImageView imageView = (ImageView) view.findViewById(R.id.iv_img);

                imageView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (findFacilitiesModels.get(position).isState()) {
                            findFacilitiesModels.get(position).setState(false);
                            buyShopAdapter.notifyDataSetChanged(findFacilitiesModels);
                        } else {
                            findFacilitiesModels.get(position).setState(true);
                            buyShopAdapter.notifyDataSetChanged(findFacilitiesModels);
                        }


                    }
                });
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });

    }

    @Override
    public void initView() {
        setBar();
        setListener();
        tv_buy_qy.setText("请选择");
        service = RequestApi.create(RequestService.class);
        areaListBeen = new ArrayList<>();
        findFacilitiesModels = new ArrayList<>();
        getphoto();//加载图片
        buyShopAdapter = new BuyShopAdapter(findFacilitiesModels, this);
        sgv_ss.setAdapter(buyShopAdapter);
        getInitFindShop();


    }

    //11.发布求租/买铺信息初始化
    private void getInitFindShop() {
        String user_id = SharePreferenceUtils.getString(SharePreferenceKey.USER_ID);

        Call<ResponseData<InitFindShopModel>> shopsListByFilter = service.getInitFindShop(user_id);
        shopsListByFilter.enqueue(new Callback<ResponseData<InitFindShopModel>>() {
            @Override
            public void onResponse(Call<ResponseData<InitFindShopModel>> call, Response<ResponseData<InitFindShopModel>> response) {

                if (response.body() != null) {
                    int total_count = response.body().getTotalcount();
                    int resultCode = response.body().getResultCode();
                    if (resultCode == 200) {
                        areaListBeen = response.body().getData().getAreaList();
                    } else {
                        showTextToast(response.body().getMessage());
                    }
                } else {
                    showTextToast("请求失败");
                }
            }

            @Override
            public void onFailure(Call<ResponseData<InitFindShopModel>> call, Throwable t) {
                showTextToast(RequestApi.detailError(t));
            }
        });
    }

    /**
     * 设置监听事件
     */
    public void setListener() {
        rel_left.setOnClickListener(this);
        ll_spinner_qy.setOnClickListener(this);
        tv_buy_publish.setOnClickListener(this);



    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.rel_left:
                finish();
                break;
            case R.id.ll_spinner_qy:
                //期望区域
                setareaListBeenPopupMenu(ll_spinner_qy);
                break;
            case R.id.tv_buy_publish:
                //发布需求
                if (buyship()) {
                    getbuyShop();
                }
                break;

        }
    }

    private void getbuyShop() {
        int buy_jg = Integer.valueOf(et_buy_jg.getText().toString());
        int buy_mj = Integer.valueOf(et_buy_mj.getText().toString());
        String buy_phone = et_buy_phone.getText().toString();
        String buy_jy = et_buy_jy.getText().toString();
        String stall = null;
        for (int i = 0; i < findFacilitiesModels.size(); i++) {
            if (findFacilitiesModels.get(i).isState()) {
                if (stall == null) {
                    stall = findFacilitiesModels.get(i).getId();
                } else {
                    stall += "," + findFacilitiesModels.get(i).getId();
                }
            }

        }

        Call<ResponseData> responseDataCall = service.getBuyFindShops("3", buy_jg, buy_mj, buy_qy, buy_phone, buy_jy, stall);
        responseDataCall.enqueue(new Callback<ResponseData>() {
            @Override
            public void onResponse(Call<ResponseData> call, Response<ResponseData> response) {
                if (response.body() != null) {
                    int total_count = response.body().getTotalcount();
                    int resultCode = response.body().getResultCode();
                    if (resultCode == 200) {
                        //成功
                        getSaleShopList();
                    } else {
                        showTextToast(response.body().getMessage());
                    }
                } else {
                    showTextToast("请求失败");
                }
            }

            @Override
            public void onFailure(Call<ResponseData> call, Throwable t) {
                showTextToast(RequestApi.detailError(t));
            }
        });

    }
    //请求推荐铺源
    private void getSaleShopList() {
        int buy_jg = Integer.valueOf(et_buy_jg.getText().toString());
        int buy_mj = Integer.valueOf(et_buy_mj.getText().toString());
        String buy_phone = et_buy_phone.getText().toString();
        String buy_jy = et_buy_jy.getText().toString();
        String stall = null;
        for (int i = 0; i < findFacilitiesModels.size(); i++) {
            if (findFacilitiesModels.get(i).isState()) {
                if (stall == null) {
                    stall = findFacilitiesModels.get(i).getId();
                } else {
                    stall += "," + findFacilitiesModels.get(i).getId();
                }
            }

        }

        Call<ResponseData<ShopsListByFilterModel>> responseDataCall = service.getSaleShopList("3", buy_jg, buy_mj, buy_qy, buy_phone, buy_jy, stall);
        responseDataCall.enqueue(new Callback<ResponseData<ShopsListByFilterModel>>() {
            @Override
            public void onResponse(Call<ResponseData<ShopsListByFilterModel>> call, Response<ResponseData<ShopsListByFilterModel>> response) {
                if (response.body() != null) {
                    int total_count = response.body().getTotalcount();
                    int resultCode = response.body().getResultCode();
                    if (resultCode == 200) {
                        //成功
                        Intent intent=new Intent(mActivity,ReleaseCompletedActivity.class);
                        intent.putExtra("RENT_SHOP_LIST", (Serializable) response.body().getData().getShopList());
                        startActivity(intent);
                    } else {
                        showTextToast(response.body().getMessage());
                    }
                } else {
                    showTextToast("请求失败");
                }
            }

            @Override
            public void onFailure(Call<ResponseData<ShopsListByFilterModel>> call, Throwable t) {
                showTextToast(RequestApi.detailError(t));
            }
        });

    }


    public boolean buyship() {
        if (TextUtils.isEmpty(et_buy_jg.getText().toString())) {
            showTextToast("请输入预算价格");
            return false;
        }

        if (TextUtils.isEmpty(et_buy_mj.getText().toString())) {
            showTextToast("请输入面积需求");
            return false;
        }

        if (buy_qy.equals("")) {
            showTextToast("请选择期望区域");
            return false;
        }

        if(!TextUtils.isEmpty(et_buy_phone.getText().toString())){
            if(isPhoneNumber(et_buy_phone.getText().toString())){

                showTextToast("请输入正确联系电话");
            }

        }

        return true;
    }


    /**
     * 判断手机号是否符合规范
     * @param phoneNo 输入的手机号
     * @return
     */
    public static boolean isPhoneNumber(String phoneNo) {
        if (TextUtils.isEmpty(phoneNo)) {
            return false;
        }
        if (phoneNo.length() == 11) {
            for (int i = 0; i < 11; i++) {
                if (!PhoneNumberUtils.isISODigit(phoneNo.charAt(i))) {
                    return false;
                }
            }
            Pattern p = Pattern.compile("^((13[^4,\\D])" + "|(134[^9,\\D])" +
                    "|(14[5,7])" +
                    "|(15[^4,\\D])" +
                    "|(17[3,6-8])" +
                    "|(18[0-9]))\\d{8}$");
            Matcher m = p.matcher(phoneNo);
            return m.matches();
        }
        return false;
    }

    //期望区域
    private void setareaListBeenPopupMenu(View view) {
        Context wrapper = new ContextThemeWrapper(mActivity, R.style.PopupMenuStyle);
        final PopupMenu popupMenu = new PopupMenu(wrapper, view);
        for (int i = 0; i < areaListBeen.size(); i++) {
            popupMenu.getMenu().add(0, i, 0, areaListBeen.get(i).getName()).setTitleCondensed(String.valueOf(areaListBeen.get(i).getId()));
        }
        popupMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
            public boolean onMenuItemClick(MenuItem item) {
                String productName = item.getTitle().toString();
                buy_qy = item.getTitleCondensed().toString();
                tv_buy_qy.setText(productName);
                return true;
            }
        });
        popupMenu.show();
    }


    private void getphoto() {
        //上水
        FindFacilitiesModel findFacilitiesModel6 = new FindFacilitiesModel();
        findFacilitiesModel6.setImg_yes(R.drawable.icon_shangshui_press);
        findFacilitiesModel6.setImg_no(R.drawable.icon_shangshui);
        findFacilitiesModel6.setState(false);
        findFacilitiesModel6.setId("9");
        findFacilitiesModels.add(findFacilitiesModel6);

        //下水
        FindFacilitiesModel findFacilitiesModel9 = new FindFacilitiesModel();
        findFacilitiesModel9.setImg_yes(R.drawable.icon_xiashui_press);
        findFacilitiesModel9.setImg_no(R.drawable.icon_xiashui);
        findFacilitiesModel9.setState(false);
        findFacilitiesModel9.setId("11");
        findFacilitiesModels.add(findFacilitiesModel9);

        //380
        FindFacilitiesModel findFacilitiesModel2 = new FindFacilitiesModel();
        findFacilitiesModel2.setImg_yes(R.drawable.icon_dian_press);
        findFacilitiesModel2.setImg_no(R.drawable.icon_dian);
        findFacilitiesModel2.setState(false);
        findFacilitiesModel2.setId("12");
        findFacilitiesModels.add(findFacilitiesModel2);

        //煤气罐
        FindFacilitiesModel findFacilitiesModel3 = new FindFacilitiesModel();
        findFacilitiesModel3.setImg_yes(R.drawable.icon_meiqi_press);
        findFacilitiesModel3.setImg_no(R.drawable.icon_meiqi);
        findFacilitiesModel3.setState(false);
        findFacilitiesModel3.setId("13");
        findFacilitiesModels.add(findFacilitiesModel3);

        //烟管道
        FindFacilitiesModel findFacilitiesModel10 = new FindFacilitiesModel();
        findFacilitiesModel10.setImg_yes(R.drawable.icon_yan_press);
        findFacilitiesModel10.setImg_no(R.drawable.icon_yan);
        findFacilitiesModel10.setState(false);
        findFacilitiesModel10.setId("14");
        findFacilitiesModels.add(findFacilitiesModel10);

        //排污管道
        FindFacilitiesModel findFacilitiesModel4 = new FindFacilitiesModel();
        findFacilitiesModel4.setImg_yes(R.drawable.icon_pai_press);
        findFacilitiesModel4.setImg_no(R.drawable.icon_pai);
        findFacilitiesModel4.setState(false);
        findFacilitiesModel4.setId("15");
        findFacilitiesModels.add(findFacilitiesModel4);
        //停车位
        FindFacilitiesModel findFacilitiesModel5 = new FindFacilitiesModel();
        findFacilitiesModel5.setImg_yes(R.drawable.icon_park_press);
        findFacilitiesModel5.setImg_no(R.drawable.icon_park);
        findFacilitiesModel5.setState(false);
        findFacilitiesModel5.setId("16");
        findFacilitiesModels.add(findFacilitiesModel5);

        //天然气
        FindFacilitiesModel findFacilitiesModel7 = new FindFacilitiesModel();
        findFacilitiesModel7.setImg_yes(R.drawable.icon_tianranqi_press);
        findFacilitiesModel7.setImg_no(R.drawable.icon_tianranqi);
        findFacilitiesModel7.setState(false);
        findFacilitiesModel7.setId("17");
        findFacilitiesModels.add(findFacilitiesModel7);

        //外摆设
        FindFacilitiesModel findFacilitiesModel8 = new FindFacilitiesModel();
        findFacilitiesModel8.setImg_yes(R.drawable.icon_waibai_press);
        findFacilitiesModel8.setImg_no(R.drawable.icon_waibai);
        findFacilitiesModel8.setState(false);
        findFacilitiesModel8.setId("18");
        findFacilitiesModels.add(findFacilitiesModel8);

        //可明火
        FindFacilitiesModel findFacilitiesModel = new FindFacilitiesModel();
        findFacilitiesModel.setImg_yes(R.drawable.icon_fire_press);
        findFacilitiesModel.setImg_no(R.drawable.icon_fire);
        findFacilitiesModel.setState(false);
        findFacilitiesModel.setId("19");
        findFacilitiesModels.add(findFacilitiesModel);

    }

    private void setBar() {
        lin_title.setVisibility(View.VISIBLE);
        lin_title.getBackground().setAlpha(255);
        int statusBarHeight1 = -1;
        //获取status_bar_height资源的ID
        int resourceId = getResources().getIdentifier("status_bar_height", "dimen", "android");
        if (resourceId > 0) {
            //根据资源ID获取响应的尺寸值
            statusBarHeight1 = getResources().getDimensionPixelSize(resourceId);
        }
        LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(lin_title.getLayoutParams());
        lp.setMargins(0, statusBarHeight1, 0, 0);
        lin_title.setLayoutParams(lp);
    }
}
